#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import signal
import time
from .log import Log
from .const import INFO

class PidMonitor():
    def __init__(self):
        self.class_name = self.__class__.__name__
        self.pid_stop = False
        self.signal_type = 0
        self.register_signal(signal.SIGINT)
        self.register_signal(signal.SIGHUP)
        self.register_signal(signal.SIGTERM)

    def my_handler(self, signum, frame):
        self.pid_stop = True
        self.signal_type = signum
        Log.do_log(INFO, self.class_name,\
            'my handler', 'stop Process:{}'.format(signum))
    
    def register_signal(self, signum):
        signal.signal(signum, self.my_handler)
   
    def run_monitor(self, name):
        if name is None:
            Log.do_log(ERROR, 
                self.class_name,
                'run_monitor', 
                'func is none possiblly due to fail to new its object')
            os.exit(1)
            return

        while True:
            if self.pid_stop:
                Log.do_log(INFO, 
                    self.class_name,
                    'my handler', 
                    'signal has been registered(signale:{})'.format(self.signal_type))
                name()
                break
            time.sleep(0.1)
